package com.igeek.health.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.igeek.health.constant.RedisConstant;
import com.igeek.health.entity.User;
import com.igeek.health.exception.HealthException;
import com.igeek.health.utils.JwtHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author fengqq
 * @Description 解析token过滤器
 * @Date 2024/9/13  15:56
 *
 * 作用：除了无需认证的请求 其他的都要解析请求头中的token，并验证合法性。继承 OncePerRequestFilter 保证请求经过过滤器一次
 *
 *
 */
@Component
public class JwtAuthenticationTokenFilter  extends OncePerRequestFilter {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //登录直接放行
        if(request.getRequestURI().equals("/admin/user/login")){
            filterChain.doFilter(request,response);
            return;
        }
        //获取请求头中token数据 若没有token则直接放行 --> 后续由security来进行认证失败处理
        //String token = request.getHeader("Authorization") Bearer xxxx 要截取出token值
        String token = request.getHeader("token"); //xxxx
        if(StrUtil.isEmpty(token)){
            //若没有token则直接放行 --> 后续由security来进行认证失败处理
            filterChain.doFilter(request,response);
            return;
        }
        //jwt将token进行解析 得到userId
        Integer userId = JwtHelper.getMemberId(token);
        if(ObjectUtil.isEmpty(userId)){
            throw new HealthException("非法token");
        }

        //从redis中 根据userIdId 获取 用户信息 （登录成功后需要将用户信息存储到redis中）
        //后台系统登录时用户信息 存储的key规则 login::user::1  {username:"",roles:{xxxx}}
        String key = RedisConstant.LOGIN_USER_TOKEN+"::"+userId;
        Object object = redisTemplate.opsForValue().get(key); //json字符串
        if(ObjectUtil.isEmpty(object)){
            throw new HealthException("redis中没有获取到后台系统的用户信息");
        }
        //获取 用户信息
        User user = JSONUtil.toBean(object.toString(), User.class);

        //若存在 则将 将Authentication对象（用户信息、已认证状态、权限信息）存入security上下文 SecurityContextHolder （后续登录成功后 某个功能需要获取当前登录人信息 则直接从security上下文来获取）
        LoginUser loginUser = new LoginUser(user);
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request,response);
    }
}
